package com.sanpu.kxe.business.trade.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sanpu.library.imagechoose.utils.PermissionsConstant;
import com.sanpu.library.imagechoose.utils.PermissionsUtils;
import com.sanpu.kxe.R;
import com.sanpu.kxe.base.BaseFragment;
import com.sanpu.kxe.base.BaseTitleActivity;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.trade.bean.RechargeDetailOutput;
import com.sanpu.kxe.business.trade.contract.ChargerTelFeeContract;
import com.sanpu.kxe.business.trade.contract.TradeConfig;
import com.sanpu.kxe.business.trade.presenter.ChargerTelFeePresenter;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.module.taglayout.FlowLayout;
import com.sanpu.kxe.module.taglayout.TagAdapter;
import com.sanpu.kxe.module.taglayout.TagFlowLayout;
import com.sanpu.kxe.module.widget.EditTextWithDel;
import com.sanpu.kxe.utils.DeviceUtil;
import com.sanpu.kxe.utils.SystemUtil;
import com.sanpu.kxe.utils.ToastUtil;

import butterknife.Bind;

/**
 * Description：话费充值
 * Created by 薛勇军 on 2019/3/20.
 */

public class ChargerTelFeeFragment extends BaseFragment implements ChargerTelFeeContract.View {

    @Bind(R.id.phone_number)
    EditTextWithDel vPhoneNumber;
    @Bind(R.id.choose_contacts)
    ImageView vChooseContacts;
    @Bind(R.id.tel_location)
    TextView vTelLocation;
    @Bind(R.id.telfee_title)
    TextView vTelTitle;
    @Bind(R.id.telfee_layout)
    LinearLayout vTelFeeLayout;
    @Bind(R.id.tag_telfee_layout)
    TagFlowLayout vTagTelfeeLayout;
    @Bind(R.id.tag_telflow_layout)
    TagFlowLayout vTagTelflowLayout;
    @Bind(R.id.telflow_title)
    TextView vTelflowTitle;
    @Bind(R.id.telflow_layout)
    LinearLayout vTelflowLayout;
    @Bind(R.id.score)
    TextView vScore;

    public static final int SCORE_CHARGER = 100;
    public static final int AMT_CHARGER = 101;

    private ChargerTelFeeContract.Presenter mPresenter;

    private String[] mContacts = new String[]{"", ""};

    private int chargerType;

    /**
     * @param type 金额充值 or 积分充值
     * @return
     */
    public static ChargerTelFeeFragment getInstance(int type) {
        ChargerTelFeeFragment fragment = new ChargerTelFeeFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(TradeConfig.INTENT_CHARGERTYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.fragment_charger_telfee;
    }

    @Override
    protected void initView() {
        super.initView();
        chargerType = getArguments().getInt(TradeConfig.INTENT_CHARGERTYPE);
        if (chargerType == SCORE_CHARGER) {
            vScore.setVisibility(View.VISIBLE);
            vTelflowLayout.setVisibility(View.GONE);
            vTagTelflowLayout.setVisibility(View.GONE);
        }
        mPresenter = new ChargerTelFeePresenter(this);
    }

    @Override
    protected void setListener() {
        super.setListener();
        vChooseContacts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!PermissionsUtils.checkReadContactsPermission(ChargerTelFeeFragment.this))
                    return;
                mPresenter.pickContact();
            }
        });

        vPhoneNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() < 11) return;
                mPresenter.getRechargeDetail(s.toString());
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        UserCenterOutput centerOutput = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (centerOutput != null && !TextUtils.isEmpty(centerOutput.getUserName())) {
            vPhoneNumber.setText(centerOutput.getUserName());
            mContacts = new String[]{"", centerOutput.getUserName()};
        }
    }

    @Override
    public void showDataView(RechargeDetailOutput rechargeDetailOutput, String phoneNumber) {
        if (rechargeDetailOutput != null) {
            createMenuView(rechargeDetailOutput);
            mContacts[1] = phoneNumber;
            vTelLocation.setText(mContacts[0] + appendTelCompany(rechargeDetailOutput) + "");
        } else {
            ToastUtil.showTextViewPrompt("没有查询到充值套餐信息！");
            vTelFeeLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 显示套餐列表
     */
    private void createMenuView(final RechargeDetailOutput detailOutput) {
        if (detailOutput.getAmountPackages() != null && detailOutput.getAmountPackages().size() > 0) {
            vTelFeeLayout.setVisibility(View.VISIBLE);
            TagAdapter tagAdapter;
            if (chargerType == AMT_CHARGER) {
                tagAdapter = new TagAdapter<RechargeDetailOutput.AmountPackage>(detailOutput.getAmountPackages()) {
                    @Override
                    public View getView(FlowLayout parent, int position, RechargeDetailOutput.AmountPackage pkg) {
                        return generateTagView(false, pkg.getPkgInfo(), pkg.getPkgPrice().toPlainString(), 0);
                    }
                };
            } else {
                tagAdapter = new TagAdapter<RechargeDetailOutput.PointPackage>(detailOutput.getPointPackages()) {
                    @Override
                    public View getView(FlowLayout parent, int position, RechargeDetailOutput.PointPackage pkg) {
                        return generateTagView(false, pkg.getPkgInfo(), null, pkg.getPkgPoint());
                    }
                };
            }
            vTagTelfeeLayout.setAdapter(tagAdapter);
        } else {
            vTelFeeLayout.setVisibility(View.GONE);
        }

        vTagTelfeeLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                String phone_number = vPhoneNumber.getText().toString();
                if (TextUtils.isEmpty(phone_number) || phone_number.length() < 11) {
                    ToastUtil.showTextViewPrompt("请填写正确的手机号码");
                    return false;
                }
                if (chargerType == AMT_CHARGER) {
                    vTagTelflowLayout.selectClear();
                    mPresenter.setupPay(vPhoneNumber.getText().toString(),
                            detailOutput.getAmountPackages().get(position), null);
                } else {
                    if (detailOutput.getCurrentPoints() < detailOutput.getPointPackages().get(position).getPkgPoint()) {
                        ToastUtil.showTextViewPrompt("积分不足");
                        return false;
                    }
                    mPresenter.setupPay(vPhoneNumber.getText().toString(),
                            null, detailOutput.getPointPackages().get(position));
                }
                return false;
            }
        });
        vTelflowLayout.setVisibility(View.GONE);
        vScore.setText("可用积分：" + detailOutput.getCurrentPoints() + "");
    }

    /**
     * 生成套餐信息的Tag
     *
     * @param isFlow 是否为流量tag
     * @param title
     * @param price
     * @return
     */
    private View generateTagView(boolean isFlow, String title, String price, int point) {
        LinearLayout view = (LinearLayout) LayoutInflater.from(getContext())
                .inflate(R.layout.layout_charger_pkg_tag, vTagTelfeeLayout, false);
        TextView titleView = view.findViewById(R.id.title);
        TextView priceView = view.findViewById(R.id.price);
        priceView.setText(price);
        if (isFlow) {
            titleView.setText(title);
            priceView.setText("售价：" + price + "元");
            priceView.setTextColor(ContextCompat.getColorStateList(getContext(), R.color.tag_price_color));
        } else {
            if (chargerType == AMT_CHARGER) {
                titleView.setText(title + ("元"));
                priceView.setVisibility(View.GONE);
            } else {
                titleView.setText("" + title + "元");
                priceView.setText("" + point + "积分兑换");
                priceView.setVisibility(View.VISIBLE);
            }
            priceView.setTextColor(ContextCompat.getColorStateList(getContext(), R.color.tag_bp_color));
        }
        int screenDp = DeviceUtil.SCREEN_WIDTH_DP - 63;
        ViewGroup.MarginLayoutParams lp =
                new ViewGroup.MarginLayoutParams(DeviceUtil.dp2px(screenDp / 3), DeviceUtil.dp2px(40));
        view.setLayoutParams(lp);
        return view;
    }

    /**
     * 拼接省、市、区
     */
    private String appendTelCompany(RechargeDetailOutput detailOutput) {
        StringBuffer sb = new StringBuffer();
        if (!TextUtils.isEmpty(detailOutput.getProvince())) {
            sb.append(detailOutput.getProvince());
        }
        if (!TextUtils.isEmpty(detailOutput.getCity())) {
            sb.append(detailOutput.getCity());
        }
        if (!TextUtils.isEmpty(detailOutput.getCompany())) {
            sb.append(detailOutput.getCompany());
        }

        if (!TextUtils.isEmpty(sb)) {
            return "(" + sb.toString() + ")";
        }
        return sb.toString();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            switch (requestCode) {
                case PermissionsConstant.REQUEST_READ_CONTACTS:
                    if (PermissionsUtils.checkReadContactsPermission(this)) {
                        mPresenter.pickContact();
                    }
                    break;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == CommonConfig.REQUESTCODE_PICK_CONTACT) {
            try {
                mContacts = SystemUtil.getPhoneContacts(getActivity(), data);
                vPhoneNumber.setText(mContacts[1]);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void showLoadingDialog(boolean cancelable) {
        ((BaseTitleActivity) getActivity()).showLoadingDialog(cancelable);
    }

    @Override
    public void setPresenter(ChargerTelFeeContract.Presenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public void showLoadingDialog(boolean cancelable, String content) {
        ((BaseTitleActivity) getActivity()).showLoadingDialog(cancelable, content);
    }

    @Override
    public void dismissLoadingDialog() {
        ((BaseTitleActivity) getActivity()).dismissLoadingDialog();
    }

    @Override
    public void showErrorText(Throwable e) {
        ((BaseTitleActivity) getActivity()).showErrorText(e);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter != null) {
            mPresenter.onDestroyPresenter();
            mPresenter = null;
        }
    }

    @Override
    protected boolean hasBindEventBus() {
        return false;
    }
}
